package cn.gongwebo.payview.widget.dialog;

import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.gongwebo.payview.R;
import cn.gongwebo.payview.util.ToastUtil;
import cn.gongwebo.payview.widget.KeyView;
import cn.gongwebo.payview.widget.PayView;

/**
 * 支付的Dialog
 * Created by GongWenBo on 2017/12/15.
 */

public class PayDialog extends DialogFragment {

    @BindView(R.id.payview)
    PayView mPayview;
        @BindView(R.id.keyview)
        KeyView mKeyview;
    private              StringBuilder sb  = new StringBuilder();
    private static final String        TAG = "PayDialog";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_pay, null);
        ButterKnife.bind(this, view);
        mKeyview.setOnKeyPressListener(new KeyView.OnKeyPressListener() {
            @Override
            public void onInertKey(String text) {
                int importCount = mPayview.getImportCount();
                mPayview.setImportCount(importCount + 1);
                sb.append(text);
                Log.d(TAG, "onInertKey: " + sb.toString());
                // 全部输入完成
                if (sb.length() == PayView.COUNT) {
                    dismiss();
                    ToastUtil.show(getActivity(), sb.toString());
                }
            }

            @Override
            public void onDeleteKey() {
                int importCount = mPayview.getImportCount();
                if (importCount >= 1) {
                    mPayview.setImportCount(importCount - 1);
                    sb.deleteCharAt(sb.length() - 1);
                    Log.d(TAG, "onDeleteKey: " + sb.toString());
                }
            }
        });
        return view;
    }

    /**
     * FragmentDialog宽高问题
     */
    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        Window window = dialog.getWindow();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.anim_dialog);
            window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            window.setBackgroundDrawableResource(android.R.color.transparent);
        }
    }

}
